<template>
  <div style="padding: 0 20px;">
    <div class="box">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <h3 style="line-height: 32px">
              品牌
            </h3>
          </div>
        </el-col>
        <el-col :span="16" style="text-align: right">
          <div class="grid-content bg-purple">
            <el-button
              size="small"
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="$router.push('/brand/add')"
            >新增品牌</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="15" class="whererow">
        <el-col :span="5" style="line-height: 32px">当前共{{ total }}个品牌。</el-col>
        <el-col :span="6">
          <el-input
            v-model="search"
            type="text"
            size="small"
            placeholder="请输入品牌名称"
          >
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </el-col>
      </el-row>
    </div>

    <!-- <el-empty
      v-if="!tableData || tableData.length == 0"
      :image-size="200"
    /> -->

    <div>
      <div class="noticerow box">
        <i class="el-icon-edit" /> &nbsp; 已选择了0项
      </div>
      <el-table
        ref="multipleTable"
        border
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" label="编号" width="60">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column align="center" label="品牌名称">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column align="center" label="首字母" width="100">
          <template slot-scope="scope">{{ scope.row.pinyin }}</template>
        </el-table-column>
        <el-table-column align="center" label="排序" width="100">
          <template slot-scope="scope">{{ scope.row.sort }}</template>
        </el-table-column>
        <el-table-column align="center" label="关键词">
          <template slot-scope="scope">{{ scope.row.keywords }}</template>
        </el-table-column>
        <el-table-column align="center" label="是否启用状态" width="130">
          <template slot-scope="scope">
            <p>
              <el-switch
                v-model="scope.row.enable"
                :active-value="1"
                :inactive-value="0"
                active-color="#1aa"
                inactive-color="#aaa"
                @change="changeSwitch(scope.$index, scope.row.id, scope.row.enable)"
              />
            </p>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="170">
          <template slot-scope="scope">
            <el-button
              title="配置类别"
              type="warning"
              size="mini"
              icon="el-icon-setting"
              circle
              @click="showBrandCategoryConfigDialog(scope.row.id)"
            />
            <el-button
              title="编辑品牌"
              type="warning"
              size="mini"
              icon="el-icon-edit"
              circle
              @click="$router.push(`/brand/edit/${scope.row.id}`)
              "
            />
            <el-button
              title="删除品牌"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              circle
              @click="deleteBrand(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          :current-page="currentPage"
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      title="为当前品牌绑定类别"
      :visible.sync="categoryBrandConfigDialogVisiable"
      :modal-append-to-body="false"
      @open="watchCategoryBrandRelationValuesChange = true"
      @close="watchCategoryBrandRelationValuesChange = false"
    >
      <el-cascader-panel
        ref="cascader"
        v-model="categoryBrandRelationValues"
        style="margin-top: 15px"
        filterable
        placeholder="试试 搜索关键字"
        :props="props"
      />
    </el-dialog>

  </div>

</template>

<script>
import * as api from '@/api/brand'
import Vue from 'vue'
import * as categoryApi from '@/api/category'
export default {
  name: 'Index',
  data: function() {
    return {
      tableData: null,
      total: 0,
      pageSize: 8,
      currentPage: 1,
      search: '',
      categoryBrandConfigDialogVisiable: false,
      categoryBrandRelationValues: [],
      watchCategoryBrandRelationValuesChange: false,
      props: {
        lazy: true, // 懒加载
        emitPath: false, // 设置 false，只返回该节点的值
        lazyLoad: (node, resolve) => {
          // node 是被选定是节点，resolve是一个回调函数，用于将数据返回给组件
          /** 定义懒加载方式 */
          console.log('选择的当前节点：', node)
          let parentId = 0
          // 当时被点击的节点不是根节点时，parentId为当前节点的id
          if (!node.root) {
            parentId = node.data.value
          }
          categoryApi.queryByParentId(parentId).then((res) => {
            console.log('加载子类别：', res)
            const children = res.data
            // 整理数据结构, 返回类别数组 [{label:'类别名', value:'类别id'}...]
            const nodes = []
            children.forEach((category) => {
              nodes.push({
                label: category.name, // 类别名称
                value: category.id, // 类别id
                leaf: category.isParent !== 1 // 是否为叶子节点
              })
            })
            console.log('整理后的类别数组：', nodes)
            // 将数据返回给组件
            resolve(nodes)
          })
        }
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    getList() {
      this.tableData = null
      this.listLoading = true
      // 调用api接口获取全部的品牌数据
      api.getPagedList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        name: this.search
      }).then(response => {
        const pagedVO = response.data
        // 将获取到的数据赋值给tableData
        this.tableData = pagedVO.data
        this.total = pagedVO.total
        this.currentPage = pagedVO.pageNum
        // this.pageSize = pagedVO.pageSize
        // this.listLoading = false
      })
    },
    changeSwitch(index, id, enable) {
      // 如果是启用状态，那么就调用禁用接口，反之亦然
      if (enable) {
        api.enableBrand(id).then(res => {
          // 设置了启用状态之后，需要重新获取品牌信息
          api.getBrand(id).then(res => {
            // 必须使用set方法更改数组内容才能被vue检测到
            Vue.set(this.tableData, index, res.data)
          })
        })
      } else {
        api.disableBrand(id).then(res => {
          // 设置了启用状态之后，需要重新获取品牌信息
          api.getBrand(id).then(res => {
            // 必须使用set方法更改数组内容才能被vue检测到
            Vue.set(this.tableData, index, res.data)
          })
        })
      }
    },
    deleteBrand(index, brand) {
      // 删除品牌之前需要先弹出确认框
      this.$confirm(`确认删除品牌 ${brand.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用api接口删除品牌
        api.deleteBrand(brand.id).then(res => {
          // 删除成功之后，需要从tableData中删除对应的数据
          this.tableData.splice(index, 1)
        })
      }).catch(() => {
        // 如果用户点击了取消按钮，那么就不做任何操作
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    showBrandCategoryConfigDialog(id) {
      this.categoryBrandConfigDialogVisiable = true
    }
  }
}
</script>

<style scoped>

</style>
